package com.synface.utils;

import android.util.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import org.json.JSONException;
import org.json.JSONObject;

public class NetUtils
{
  private static final String TAG = NetUtils.class.getSimpleName();
  private static final String AUTH_URL = "http://182.18.19.136:6199/hrs/authorizelog/authorize";
  private String mAppId;
  private int mHttpStatus;
  private String mResponse;

  public NetUtils()
  {
    this.mAppId = "d6d8dd1b-538a-4305-8adb-c6e08cbe5926";
  }

  public int getHttpStatus()
  {
    return this.mHttpStatus;
  }

  public String getResponse() {
    return this.mResponse;
  }

  public void authByHttpPost(String param) {
    try {
      URL url = new URL("http://182.18.19.136:6199/hrs/authorizelog/authorize");

      HttpURLConnection httpURLConnection = (HttpURLConnection)url
        .openConnection();

      httpURLConnection.setConnectTimeout(5000);

      httpURLConnection.setReadTimeout(10000);

      httpURLConnection.setDoOutput(true);

      httpURLConnection.setRequestMethod("POST");
      httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      PrintWriter out = new PrintWriter(httpURLConnection
        .getOutputStream());

      byte[] encryptResult = JavaAESCryptor.encrypt(param
        .getBytes("UTF-8"));

      String sendBase64 = Base64.encodeToString(encryptResult, 0);

      out.print("reqJson=" + sendBase64);
      out.flush();

      out.close();

      this.mHttpStatus = httpURLConnection.getResponseCode();
      if (this.mHttpStatus == 200) {
        InputStream is = httpURLConnection.getInputStream();

        this.mResponse = URLDecoder.decode(readInStream(is), "utf-8");
        is.close();
      }
      else {
        System.out.println("通信错误：" + this.mHttpStatus);
      }
    } catch (IOException e) {
      this.mHttpStatus = -1;
      e.printStackTrace();
    }
  }

  public String getSendData(String appId, int type, String returnCode, String version, String deviceName)
  {
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("appId", appId);
      jsonObject.put("type", type);
      jsonObject.put("code", returnCode);
      jsonObject.put("version", version);
      jsonObject.put("deviceName", deviceName);

      return jsonObject.toString();
    } catch (JSONException e) {
      e.printStackTrace();
    }return null;
  }

  private String readInStream(InputStream in) throws IOException
  {
    String resultData = "";
    InputStreamReader ins = new InputStreamReader(in);
    BufferedReader buffer = new BufferedReader(ins);
    String inputLine = null;
    while ((inputLine = buffer.readLine()) != null) {
      resultData = resultData + inputLine + "\n";
    }
    return resultData;
  }
}